import { message } from 'ant-design-vue'
import axios from 'axios'
import Vue from 'vue'
import VueRouter from 'vue-router'
import router from '../router'
import store from '@/store'

Vue.use(VueRouter)

// 新建axios实例
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 20000
})

let isRefreshingToken = false
let requestsQueue = []
// 添加请求拦截器
instance.interceptors.request.use(config => {
  console.log('dfsjdfsj')
  const accessToken = store.state.user.accessToken
  if (accessToken) {
    config.headers.authorization = `Bearer ${accessToken}`
  }

  // 当接收到401且正在刷新token时，将请求放入队列
  if (!accessToken && !isRefreshingToken && store.state.user.refreshToken) {
    requestsQueue.push(config)
    return new Promise(resolve => { })
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 添加相应拦截器
instance.interceptors.response.use(response => {
  const { code, Msg, notShow } = response.data
  if (!notShow) {
    message.destroy()
    if (code === '1') {
      message.success(Msg || '成功')
    } else if (code === '0') {
      message.info(Msg || '暂无数据')
    } else if (code === '-1') {
      message.error(Msg || '失败')
    }
  }

  return response
}, async (error) => {
  const originalRequest = error.config

  if (error.response.status === 401 && store.state.user.refreshToken && !isRefreshingToken) {
    isRefreshingToken = true
    console.log(1)
    try {
      console.log(2)

      const refreshResponse = await instance.post('/api/adminApi/FrontEndQuestions/refresh', { refreshToken: store.state.user.refreshToken })
      console.log(refreshResponse)
      console.log(3)

      if (refreshResponse.data.success) {
        store.state.user.accessToken = refreshResponse.data.accessToken
        localStorage.setItem(store.state.user.storageKeys.accessToken, store.state.user.accessToken)
        // 使用新的token重新发起队列中的请求
        requestsQueue.forEach(request => {
          request.headers.authorization = `Bearer ${store.state.user.accessToken}`
          instance(request)
        })
        requestsQueue = [] // 清空队列
        originalRequest.headers.authorization = `Bearer ${store.state.user.accessToken}`
        console.log('dsdksj')
        return instance(originalRequest)
      } else {
        console.log('Refresh token failed - server did not return success.')
        store.commit('user/clearTokens')
      }
    } catch (refreshError) {
      // console.error('Refresh token failed with error:', refreshError.message, refreshError.response ? refreshError.response.data : '')
      message.info('登陆过期，请重新登陆')
      store.commit('user/clearTokens')
      router.push('/login') // 假设登录页面的路径是/login
    } finally {
      isRefreshingToken = false
    }
  } else {
    console.log('No refresh token available or status code is not 401.')
  }

  return Promise.reject(error)
})

export default instance
